package tool

/**
告警模块

**/

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"ulcdkey/conf"
)

var LastSendWarnTime time.Time
var IsPrintLog = true

func init() {

	LastSendWarnTime = time.Now().Add(time.Duration(-1) * time.Hour)
}

//日志输出
func LogRecord(log ...interface{}) {
	if IsPrintLog {
		fmt.Print("\n", GetTime("2006-01-02 15:04:05:"), " ")
		fmt.Println(log...)
	}
}

//时间获取方法
func GetTime(format string) string {
	nowTime := time.Now().Unix()
	t := time.Unix(nowTime, 0)
	//2006-01-02 15:04:05
	nt := t.Format(format)
	return nt
}

//
func SendWarn(emailTitle string, emailMsg string) {
	dt := time.Since(LastSendWarnTime).Seconds()
	if dt < conf.Conf.WarnConfig.Duration {
		//距离上一次报警太短
		return
	}
	LastSendWarnTime = time.Now()

	//另开一个线程发警告
	go func() {

		typeMsg := "CDKey服务器 异常报警"
		otherMsg := ""
		sendTime := GetTime("2006-01-02 15:04:05")

		data := fmt.Sprintf("typeMsg=%s&emailTitle=%s&emailMsg=%s&otherMsg=%s&sendTime=%s&partyId=%s",
			typeMsg,
			emailTitle,
			emailMsg,
			otherMsg,
			sendTime,
			conf.Conf.WarnConfig.PartyId)

		resp, err := http.Post(conf.Conf.WarnConfig.Url, "application/x-www-form-urlencoded", strings.NewReader(data))
		if err != nil {
			LogRecord("SendWarn：发送邮件失败--", err.Error())
			return
		}

		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			LogRecord("SendWarn：读取body失败--", err.Error())
			return
		}

		var respMap map[string]string

		jsonErr := json.Unmarshal(body, &respMap)

		if jsonErr != nil {
			LogRecord("SendWarn：body json 解析失败--", jsonErr.Error())
			return
		}

		if respMap["code"] != "1" {
			LogRecord("SendWarn：邮件发送失败--", respMap)
			return
		}
		LogRecord("SendWarn：邮件发送成功")

	}()

}
